package zyqks;

import java.util.Scanner;
/**
 * 通过构建边和点的对象来创建图
 * @author King
 */
public class CreateGraph {

    /**
     * 根据顶点信息String，返回边的对象
     * @param graph 图
     * @param str 顶点名称
     * @return 返回的是边对象的标签
     */
    public int vtoe(Graph graph,String str){
        for(int i=0;i<graph.vertexNum;i++){
            if(graph.vertexList.get(i).vertexName.equals(str)){
                return i;
            }
        }
        return -1;
    }

    /**
     * 该函数用于图的初始化的实现
     * @param graph 图
     */
    public void initialGraph(Graph graph){
        @SuppressWarnings("resource")
        Scanner scan=new Scanner(System.in);
        System.out.println("请输入顶点数和边数：");
        graph.vertexNum=scan.nextInt();
        graph.edgeNum=scan.nextInt();

        System.out.println("请依次输入定点名称：");
        for(int i=0;i<graph.vertexNum;i++){
            Vertex vertex=new Vertex();
            String name=scan.next();
            vertex.vertexName=name;
            vertex.firstEdge=null;
            graph.vertexList.add(vertex);
        }

        System.out.println("请依次输入每个边：");
        for(int i=0;i<graph.edgeNum;i++){
            String preV=scan.next();
            String folV=scan.next();
            int v1=vtoe(graph,preV);
            int v2=vtoe(graph,folV);
            if(v1==-1 || v2==-1)
                System.out.println("输入顶点数据错误！");

//下面代码是图构建的核心：链表操作
            Edge edge1=new Edge();
            edge1.edgeName=v2;
            edge1.next=graph.vertexList.get(v1).firstEdge;
            graph.vertexList.get(v1).firstEdge=edge1;

//          下面代码加上便是构建无向图，不加便是构建有向图
//          Edge edge2=new Edge();
//          edge2.edgeName=v1;
//          edge2.next=graph.vertexList.get(v2).firstEdge;
//          graph.vertexList.get(v2).firstEdge=edge2;
        }
    }

    /**
     * 输出图的邻接链表表示
     * @param graph 图
     */
    public void outputGraph(Graph graph){
        Edge edge=new Edge();
        for(int i=0;i<graph.vertexNum;i++){
            System.out.print(graph.vertexList.get(i).vertexName);

            edge=graph.vertexList.get(i).firstEdge;
            while(edge!=null){
                System.out.print("-->"+graph.vertexList.get(edge.edgeName).vertexName);
                edge=edge.next;
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        CreateGraph createGraph=new CreateGraph();
        Graph graph=new Graph();
        createGraph.initialGraph(graph);
        createGraph.outputGraph(graph);
    }

}
